package cn.hy.preparelesson.common.service;

import cn.hy.pms.thrift.SysUserThrift;
import cn.hy.pms.thrift.utils.ThriftUtils;
import cn.hy.preparelesson.common.entity.*;
import cn.hy.preparelesson.common.enums.DataStatus;
import cn.hy.preparelesson.common.exception.MessageException;
import cn.hy.preparelesson.common.mapper.PlLessonMapper;
import cn.hy.preparelesson.common.params.PageParams;
import cn.hy.preparelesson.common.utils.IdUtils;
import cn.hy.preparelesson.common.utils.PageInfoUtils;
import cn.hy.preparelesson.common.utils.UserInfoUtils;
import cn.hy.preparelesson.common.utils.UserUtils;
import cn.hy.preparelesson.common.vo.*;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 备课 Service
 */
@Service
public class PlLessonService extends  BaseService{
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    PlLessonMapper plLessonMapper;

    @Autowired
    PlLessonClassDetailService plLessonClassDetailService;

    @Autowired
    PlLessonFileService plLessonFileService;

    @Autowired
    PlPostScriptService plPostScriptService;

    @Autowired
    PlCommentService plCommentService;




    /**
     * 分页获取我的备课信息
     * @param schoolId
     * @param pageParams
     * @param title
     * @param createStartTime
     * @param schoolYear
     * @param subjectId
     * @param term
     * @param createEndTime
     * @param distanceYear
     * @param classId
     * @return
     */
    public PageInfo<PlLesson> findValidPageV4By(String schoolId, PageParams pageParams, String title,  Date createStartTime,Integer schoolYear, String subjectId, Byte term, Date createEndTime,
                                                    BigDecimal distanceYear, String classId, String createdBy) throws TException {
        List<String> lessonIdList = new ArrayList<>();
        if (distanceYear != null || StringUtils.isNotBlank(classId)) {
            List<PlLessonClassDetail> plClassList = plLessonClassDetailService.findPlCDListByLessonIdInAndBy(schoolId, null, distanceYear, classId);
            if (CollectionUtils.isEmpty(plClassList)) {
                return new PageInfo<>();
            }
            lessonIdList = plClassList.stream().map(PlLessonClassDetail::getLessonId).collect(Collectors.toList());
        }

        PageHelper.startPage(pageParams);
        PageInfo<PlLesson> pageInfo = new PageInfo<>(findNormalListBy(schoolId, title, createStartTime, schoolYear, subjectId, term, createEndTime, createdBy, lessonIdList));

        if (pageInfo.getList() != null && !CollectionUtils.isEmpty(pageInfo.getList())) {
            List<PlLesson> lessonList = pageInfo.getList();

            //个人备课，创建人名称为当前用户名称
            if (StringUtils.isNotBlank(createdBy)) {
                List<SysUserIdAndNameVo> createByList = ThriftUtils.findUserNameByUserIdList(Arrays.asList(createdBy));
                String userName = createByList.get(0).getName();
                lessonList.stream().forEach(item -> item.setCreateName(userName));
            } else {
                //全校备课
                UserInfoUtils.buildUserName(lessonList, "getCreateBy", "setCreateName");
            }

            //查询备课 班级关联关系
            List<String> plLessonIdList = lessonList.stream().map(PlLesson::getId).collect(Collectors.toList());
            List<PlLessonClassDetail> plClassList = plLessonClassDetailService.findPlCDListByLessonIdInAndBy(schoolId, plLessonIdList, null, null);
            if (!CollectionUtils.isEmpty(plClassList)) {
                Map<String, List<PlLessonClassDetail>> plLCDMap = plClassList.stream().collect(Collectors.groupingBy(PlLessonClassDetail::getLessonId));
                for (Map.Entry<String, List<PlLessonClassDetail>> plLCD : plLCDMap.entrySet()) {
                    String plLCDLessonId = plLCD.getKey(); //备课 - 班级 lessonId
                    PlLesson plLessonTemp = lessonList.stream().filter(plLesson -> plLesson.getId().equals(plLCDLessonId)).findFirst().orElse(null);
                    if (plLessonTemp != null) {
                        List<PlLessonClassDetail> plPCDList = plLCD.getValue();
                        plLessonTemp.setClassNameStr(String.join(",", plPCDList.stream().map(PlLessonClassDetail::getClassCode).collect(Collectors.toList())));
                        plLessonTemp.setGradeName(Optional.ofNullable(plPCDList.get(0).getGradeName()).orElse(null));
                    }
                }
            }

            //备课-后记集合
            List<PlPostscript> plPostscriptList = plPostScriptService.findValidListBySchoolIdAndLessonIdIn(schoolId, plLessonIdList);
            //备课-评论集合
            List<PlComment> plCommentList = plCommentService.findValidListBySchoolIdAndLessonIdIn(schoolId, plLessonIdList);


            //默认备课都可添加后记，可删除
            for (PlLesson lesson : lessonList)  {
                lesson.setCanDelete(true);
                lesson.setCanAddPostScript(true);
            }

            //备课存在评论或者后记 则该备课信息不能删除(默认值 都为 true)
            if (!CollectionUtils.isEmpty(plPostscriptList)) {
                for (PlLesson lesson : lessonList) {
                    PlPostscript tempPostscript = plPostscriptList.stream().filter(postscript -> lesson.getId().equals(postscript.getLessonId())).findFirst().orElse(null);
                    if (tempPostscript != null) {
                        lesson.setCanDelete(false);
                        lesson.setCanAddPostScript(false);
                    }
                }
            }

            if (!CollectionUtils.isEmpty(plCommentList)) {
                for (PlLesson lesson : lessonList) {
                    plCommentList.stream().filter(plComment -> plComment.getLessonId().equals(lesson.getId())).findFirst().ifPresent(plCommentTemp -> lesson.setCanDelete(false));
                }
            }
        }
        return pageInfo;
    }

    /**
     * 分页获取我的备课信息
     * @param schoolId
     * @param pageParams
     * @param title
     * @param createStartTime
     * @param schoolYear
     * @param subjectId
     * @param term
     * @param createEndTime
     * @param distanceYear
     * @param classId
     * @return
     */
    @Deprecated
    public PageInfo<PlLesson> findValidPageBy(String schoolId, PageParams pageParams, String title,  Date createStartTime,Integer schoolYear, String subjectId, Byte term, Date createEndTime,
                                                    BigDecimal distanceYear, String classId, String createdBy) throws TException {
        List<String> lessonIdList = new ArrayList<>();
        if (distanceYear != null || StringUtils.isNotBlank(classId)) {
            List<PlLessonClassDetail> plClassList = plLessonClassDetailService.findPlCDListByLessonIdInAndBy(schoolId, null, distanceYear,  classId);
            if (CollectionUtils.isEmpty(plClassList)) {
                return new PageInfo<>();
            }
            lessonIdList = plClassList.stream().map(PlLessonClassDetail::getLessonId).collect(Collectors.toList());
        }

        PageHelper.startPage(pageParams);
        PageInfo<PlLesson> pageInfo = new PageInfo<>(findNormalListBy(schoolId, title, createStartTime, schoolYear, subjectId, term, createEndTime, createdBy, lessonIdList));
        if (pageInfo.getList() == null || CollectionUtils.isEmpty(pageInfo.getList())) {
            return new PageInfo<>();
        }
        List<PlLesson> lessonList = pageInfo.getList();
        if (StringUtils.isNotBlank(createdBy)) {
            //个人备课 创建人名称为当前用户名称
            List<SysUserIdAndNameVo> createByList = ThriftUtils.findUserNameByUserIdList(Arrays.asList(createdBy));
            String userName = createByList.get(0).getName();
            lessonList.forEach(item -> item.setCreateName(userName));
        } else {
            List<String> createByList = lessonList.stream().map(PlLesson::getCreateBy).collect(Collectors.toList());
            List<SysUserIdAndNameVo> userNameByUserIdList = ThriftUtils.findUserNameByUserIdList(createByList);
            for (PlLesson lesson : lessonList) {
                SysUserIdAndNameVo sysUserIdAndNameVo = userNameByUserIdList.stream().filter(user -> lesson.getCreateBy().equals(user.getUserId())).findFirst().orElse(null);
                if (sysUserIdAndNameVo != null) {
                    lesson.setCreateName(sysUserIdAndNameVo.getName());
                } else {
                    lesson.setCreateName("该账号已注销");
                }
            }
        }
        List<String> plLessonIdList = lessonList.stream().map(PlLesson::getId).collect(Collectors.toList());
        List<PlLessonClassDetail> plClassList = plLessonClassDetailService.findPlCDListByLessonIdInAndBy(schoolId, plLessonIdList, null,  null);

        if (CollectionUtils.isEmpty(plClassList)) {
            return new PageInfo<>();
        }

        List<PlLessonListVo> plLessonListVoList = new ArrayList<>();
        Map<String, List<PlLessonClassDetail>> plLCDMap = plClassList.stream().collect(Collectors.groupingBy(PlLessonClassDetail::getLessonId));
        for (Map.Entry<String, List<PlLessonClassDetail>> plLCD : plLCDMap.entrySet() ) {
            String plLCDLessonId = plLCD.getKey(); //备课 - 班级 lessonId
            PlLesson plLessonTemp = lessonList.stream().filter(plLesson -> plLesson.getId().equals(plLCDLessonId)).findFirst().orElse(null);
            if (plLessonTemp != null) {
                PlLessonListVo plLessonListVo = new PlLessonListVo();
                BeanUtils.copyProperties(plLessonTemp, plLessonListVo);
                List<PlLessonClassDetail> plPCDList = plLCD.getValue(); // 备课-班级 list
                String classNameStr = String.join(",", plPCDList.stream().map(PlLessonClassDetail::getClassCode).collect(Collectors.toList()));
                plLessonListVo.setClassNameStr(classNameStr);
                plLessonListVo.setGradeName(Optional.of(plPCDList.get(0).getGradeName()).orElse(null));
                plLessonListVoList.add(plLessonListVo);
            }
        }
        if(CollectionUtils.isEmpty(plLessonListVoList)) {
            return new PageInfo<>();
        }


        //备课-后记集合
        List<PlPostscript> plPostscriptList = plPostScriptService.findValidListBySchoolIdAndLessonIdIn(schoolId, plLessonIdList);
        //备课-评论集合
        List<PlComment> plCommentList = plCommentService.findValidListBySchoolIdAndLessonIdIn(schoolId, plLessonIdList);

        //备课存在评论或者后记 则该备课信息不能删除

        if (CollectionUtils.isEmpty(plPostscriptList) && CollectionUtils.isEmpty(plCommentList)) {
            plLessonListVoList.forEach(item -> {
                item.setCanDelete(true);
                item.setCanAddPostScript(true);
            });
        }
        if (!CollectionUtils.isEmpty(plPostscriptList) && !CollectionUtils.isEmpty(plCommentList)) {
            for (PlLessonListVo plLessonListVo : plLessonListVoList) {
                String tempLessonId = plLessonListVo.getId();
                PlPostscript plPostscript = plPostscriptList.stream().filter(postscript -> tempLessonId.equals(postscript.getLessonId())).findFirst().orElse(null);
                if (plPostscript != null) {
                    plLessonListVo.setCanDelete(false);
                    plLessonListVo.setCanAddPostScript(false);
                    continue;
                }
                PlComment tempPlComment = plCommentList.stream().filter(plComment -> tempLessonId.equals(plComment.getLessonId())).findFirst().orElse(null);
                if (tempPlComment != null) {
                    plLessonListVo.setCanDelete(false);
                    plLessonListVo.setCanAddPostScript(true);
                    continue;
                }
                plLessonListVo.setCanDelete(true);
                plLessonListVo.setCanAddPostScript(true);
            }
        }

        if (CollectionUtils.isEmpty(plPostscriptList) && !CollectionUtils.isEmpty(plCommentList)) {
            for (PlLessonListVo plLessonListVo : plLessonListVoList) {
                String tempLessonId = plLessonListVo.getId();
                PlComment tempPlComment = plCommentList.stream().filter(plComment -> tempLessonId.equals(plComment.getLessonId())).findFirst().orElse(null);
                if (tempPlComment != null) {
                    plLessonListVo.setCanDelete(false);
                } else {
                    plLessonListVo.setCanDelete(true);
                }
                plLessonListVo.setCanAddPostScript(true);
            }
        }
        if (!CollectionUtils.isEmpty(plPostscriptList) && CollectionUtils.isEmpty(plCommentList)) {
            for (PlLessonListVo plLessonListVo : plLessonListVoList) {
                String tempLessonId = plLessonListVo.getId();
                PlPostscript plPostscript = plPostscriptList.stream().filter(postscript -> tempLessonId.equals(postscript.getLessonId())).findFirst().orElse(null);
                if (plPostscript != null) {
                    plLessonListVo.setCanDelete(false);
                    plLessonListVo.setCanAddPostScript(false);
                } else {
                    plLessonListVo.setCanDelete(true);
                    plLessonListVo.setCanAddPostScript(true);
                }
            }
        }

        pageInfo.setList(plLessonListVoList.stream().sorted(Comparator.comparing(PlLessonListVo::getCreateAt).reversed()).collect(Collectors.toList()));
        return pageInfo;
    }

    /**
     * 获取备课信息
     * @param schoolId
     * @param title
     * @param createStartTime
     * @param schoolYear
     * @param subjectId
     * @param term
     * @param createEndTime
     * @param createdBy
     * @param lessonIdList
     * @return
     */
    public List<PlLesson> findNormalListBy(String schoolId, String title,  Date createStartTime,Integer schoolYear, String subjectId, Byte term, Date createEndTime,
                                            String createdBy, List<String> lessonIdList) {
        PlLessonExample example = new PlLessonExample();
        PlLessonExample.Criteria criteria = example.createCriteria();
        criteria.andSchoolIdEqualTo(schoolId).andStatusEqualTo(DataStatus.NORMAL.getCode());
        if (StringUtils.isNotBlank(createdBy)) {
            criteria.andCreateByEqualTo(createdBy);
        }
        if (StringUtils.isNotBlank(title)) {
            criteria.andTitleLike("%" + title + "%");
        }
        if (createStartTime != null) {
            criteria.andCreateAtGreaterThanOrEqualTo(createStartTime);
        }
        if (createEndTime != null) {
            criteria.andCreateAtLessThanOrEqualTo(createEndTime);
        }
        if (schoolYear != null) {
            criteria.andSchoolYearEqualTo(schoolYear);
        }
        if (term != null) {
            criteria.andTermEqualTo(term);
        }
        if (StringUtils.isNotBlank(subjectId)) {
            criteria.andSubjectIdEqualTo(subjectId);
        }
        if (!CollectionUtils.isEmpty(lessonIdList)) {
            criteria.andIdIn(lessonIdList);
        }
        example.setOrderByClause("create_at desc");
       return  plLessonMapper.selectByExampleWithBLOBs(example);

    }



    /**
     * 查询备课集合
     * @param schoolId
     * @param title
     * @param createStartTime
     * @param schoolYear
     * @param subjectId
     * @param term
     * @param createEndTime
     * @param distanceYear
     * @param classId
     * @return
     */
    public List<PlLessonListVo> findValidPlLessonListBy(String schoolId, String title,  Date createStartTime, Date createEndTime, Integer schoolYear, String subjectId, Byte term,
                                                        BigDecimal distanceYear, String classId, String createdBy) {
     PlLessonExample example = new PlLessonExample();
     PlLessonExample.Criteria criteria = example.createCriteria();
        criteria.andSchoolIdEqualTo(schoolId).andStatusEqualTo(DataStatus.NORMAL.getCode());
        if (StringUtils.isNotBlank(createdBy)) {
            criteria.andCreateByEqualTo(createdBy);
        }
        if (StringUtils.isNotBlank(title)) {
            criteria.andTitleLike("%" + title + "%");
        }
        if (createStartTime != null) {
            criteria.andCreateAtGreaterThanOrEqualTo(createStartTime);
        }
        if (createEndTime != null) {
            criteria.andCreateAtLessThanOrEqualTo(createEndTime);
        }
        if (schoolYear != null) {
            criteria.andSchoolYearEqualTo(schoolYear);
        }
        if (term != null) {
            criteria.andTermEqualTo(term);
        }
        if (StringUtils.isNotBlank(subjectId)) {
            criteria.andSubjectIdEqualTo(subjectId);
        }
        example.setOrderByClause("create_at desc");
        List<PlLesson> plLessonList = plLessonMapper.selectByExampleWithBLOBs(example);
        if (CollectionUtils.isEmpty(plLessonList)) {
            return new ArrayList<>();
        }
        if (StringUtils.isNotBlank(createdBy)) {
            //个人备课 创建人名称为当前用户名称
            plLessonList.stream().forEach(item -> item.setCreateName(UserUtils.getUsername()));
        } else {
            // todo 查库
        }

        List<String> plLessonIdList = plLessonList.stream().map(PlLesson::getId).collect(Collectors.toList());
        List<PlLessonClassDetail> plClassList = plLessonClassDetailService.findPlCDListByLessonIdInAndBy(schoolId, plLessonIdList, distanceYear,  classId);
        if (CollectionUtils.isEmpty(plClassList)) {
            return new ArrayList<>();
        }

        List<PlLessonListVo> plLessonListVoList = new ArrayList<>();
        Map<String, List<PlLessonClassDetail>> plLCDMap = plClassList.stream().collect(Collectors.groupingBy(PlLessonClassDetail::getLessonId));
        for (Map.Entry<String, List<PlLessonClassDetail>> plLCD : plLCDMap.entrySet() ) {
            String plLCDLessonId = plLCD.getKey(); //备课 - 班级 lessonId
            PlLesson plLessonTemp = plLessonList.stream().filter(plLesson -> plLesson.getId().equals(plLCDLessonId)).findFirst().orElse(null);
            if (plLessonTemp != null) {
                PlLessonListVo plLessonListVo = new PlLessonListVo();
                BeanUtils.copyProperties(plLessonTemp, plLessonListVo);
                List<PlLessonClassDetail> plPCDList = plLCD.getValue(); // 备课-班级 list
                String classNameStr = String.join(",", plPCDList.stream().map(PlLessonClassDetail::getClassCode).collect(Collectors.toList()));
                plLessonListVo.setClassNameStr(classNameStr);
                plLessonListVo.setGradeName(Optional.of(plPCDList.get(0).getGradeName()).orElse(null));
                plLessonListVoList.add(plLessonListVo);
            }
        }
        if(CollectionUtils.isEmpty(plLessonListVoList)) {
            return new ArrayList<>();
        }


        //备课-后记集合
        List<PlPostscript> plPostscriptList = plPostScriptService.findValidListBySchoolIdAndLessonIdIn(schoolId, plLessonIdList);
        //备课-评论集合
        List<PlComment> plCommentList = plCommentService.findValidListBySchoolIdAndLessonIdIn(schoolId, plLessonIdList);

        //备课存在评论或者后记 则该备课信息不能删除

        if (CollectionUtils.isEmpty(plPostscriptList) && CollectionUtils.isEmpty(plCommentList)) {
            plLessonListVoList.stream().forEach(item -> {
                item.setCanDelete(true);
                item.setCanAddPostScript(true);
            });
        }
        if (!CollectionUtils.isEmpty(plPostscriptList) && !CollectionUtils.isEmpty(plCommentList)) {
            for (PlLessonListVo plLessonListVo : plLessonListVoList) {
                String tempLessonId = plLessonListVo.getId();
                PlPostscript plPostscript = plPostscriptList.stream().filter(postscript -> tempLessonId.equals(postscript.getLessonId())).findFirst().orElse(null);
                if (plPostscript != null) {
                    plLessonListVo.setCanDelete(false);
                    plLessonListVo.setCanAddPostScript(false);
                    continue;
                }
                PlComment tempPlComment = plCommentList.stream().filter(plComment -> tempLessonId.equals(plComment.getLessonId())).findFirst().orElse(null);
                if (tempPlComment != null) {
                    plLessonListVo.setCanDelete(false);
                    plLessonListVo.setCanAddPostScript(true);
                    continue;
                }
                plLessonListVo.setCanDelete(true);
                plLessonListVo.setCanAddPostScript(true);
            }
        }

        if (CollectionUtils.isEmpty(plPostscriptList) && !CollectionUtils.isEmpty(plCommentList)) {
            for (PlLessonListVo plLessonListVo : plLessonListVoList) {
                String tempLessonId = plLessonListVo.getId();
                PlComment tempPlComment = plCommentList.stream().filter(plComment -> tempLessonId.equals(plComment.getLessonId())).findFirst().orElse(null);
                if (tempPlComment != null) {
                    plLessonListVo.setCanDelete(false);
                } else {
                    plLessonListVo.setCanDelete(true);
                }
                plLessonListVo.setCanAddPostScript(true);
            }
        }
        if (!CollectionUtils.isEmpty(plPostscriptList) && CollectionUtils.isEmpty(plCommentList)) {
            for (PlLessonListVo plLessonListVo : plLessonListVoList) {
                String tempLessonId = plLessonListVo.getId();
                PlPostscript plPostscript = plPostscriptList.stream().filter(postscript -> tempLessonId.equals(postscript.getLessonId())).findFirst().orElse(null);
                if (plPostscript != null) {
                    plLessonListVo.setCanDelete(false);
                    plLessonListVo.setCanAddPostScript(false);
                } else {
                    plLessonListVo.setCanDelete(true);
                    plLessonListVo.setCanAddPostScript(true);
                }
            }
        }

        return plLessonListVoList.stream().sorted(Comparator.comparing(PlLessonListVo::getCreateAt).reversed()).collect(Collectors.toList());
    }


    /**
     * 保存备课信息
     * @param schoolId
     * @param opeUserId
     * @param lessonSaveVo
     */
    @Transactional(rollbackFor = Exception.class)
    public void save(String schoolId, String opeUserId, LessonSaveVo lessonSaveVo, List<ClassVo> classVoList,  List<FilePlLessonVo> filePlLessonVoList) {
        PlLesson plLesson = new PlLesson();
        String id = IdUtils.newId();
        Date now  = new Date();
        plLesson.setId(id);
        plLesson.setTitle(lessonSaveVo.getTitle());
        plLesson.setContent(Optional.of(lessonSaveVo.getContent()).orElse(null));
        plLesson.setSchoolId(schoolId);
        plLesson.setSchoolYear(lessonSaveVo.getSchoolYear());
        plLesson.setType(lessonSaveVo.getType());
        plLesson.setSemesterId(lessonSaveVo.getSemesterId());
        plLesson.setTerm(lessonSaveVo.getTerm());
        plLesson.setSubjectId(lessonSaveVo.getSubjectId());
        plLesson.setSubjectCode(lessonSaveVo.getSubjectCode());
        plLesson.setSubjectLevel(lessonSaveVo.getSubjectLevel());
        plLesson.setSubjectType(lessonSaveVo.getSubjectType());
        plLesson.setSubjectName(lessonSaveVo.getSubjectName());
        plLesson.setUpdateBy(opeUserId);
        plLesson.setCreateBy(opeUserId);
        plLesson.setCreateAt(now);
        plLesson.setCreateName(UserUtils.getUsername());
        plLesson.setUpdateAt(now);
        plLesson.setStatus(DataStatus.NORMAL.getCode());
        plLessonMapper.insert(plLesson);
        //保存备课班级关联信息
        buildAndSavePlLessonClassDetail(schoolId, opeUserId, id, classVoList, now);
        //文件列表保存
        if(!CollectionUtils.isEmpty(filePlLessonVoList)) {
            buildAndSavePlLessonFileDetail(schoolId, opeUserId, id, filePlLessonVoList, now);
        }
    }

    /**
     * 修改备课信息
     * @param schoolId
     * @param opeUserId
     * @param lessonSaveVo
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(String schoolId, String opeUserId, LessonSaveVo lessonSaveVo, List<ClassVo> classVoList) {
        PlLesson curPlLesson = findValidPlLessonBySchoolIdAndId(schoolId, lessonSaveVo.getId());
        if (curPlLesson == null) {
            throw  new MessageException("备课信息不存在");
        }
        curPlLesson.setTitle(lessonSaveVo.getTitle());
        curPlLesson.setContent(lessonSaveVo.getContent());
        curPlLesson.setType(lessonSaveVo.getType());
        curPlLesson.setSemesterId(lessonSaveVo.getSemesterId());
        curPlLesson.setTerm(lessonSaveVo.getTerm());
        curPlLesson.setSchoolYear(lessonSaveVo.getSchoolYear());
        curPlLesson.setSubjectId(lessonSaveVo.getSubjectId());
        curPlLesson.setSubjectName(lessonSaveVo.getSubjectName());
        curPlLesson.setSubjectCode(lessonSaveVo.getSubjectCode());
        curPlLesson.setSubjectType(lessonSaveVo.getSubjectType());
        curPlLesson.setSubjectLevel(lessonSaveVo.getSubjectLevel());
        curPlLesson.setUpdateAt(new Date());
        curPlLesson.setUpdateBy(opeUserId);
        plLessonMapper.updateByPrimaryKeyWithBLOBs(curPlLesson);
        //修改备课-班级信息
        plLessonClassDetailService.batchUpdatePlLessonClassDetail(schoolId, opeUserId, curPlLesson.getId(),  classVoList, new Date());

        //修改附件信息
        plLessonFileService.batchUpdatePlLessonFile(schoolId, opeUserId, curPlLesson.getId(), Optional.of(lessonSaveVo.getAnndexList()).orElse(null), new Date() );
    }

    /**
     * 根据schoolId, lessonId查询备课以及备课其他属性详情
     * @param schoolId
     * @param lessonId
     * @return
     */
    public PlPrepareLessonDetailVo findVaildPlLessonDetailBySchoolIdAndId(String schoolId, String lessonId) throws TException {
        PlPrepareLessonDetailVo plPrepareLessonDetail = new PlPrepareLessonDetailVo();

        PlLesson curPlLesson = findValidPlLessonBySchoolIdAndId(schoolId, lessonId);
        if(curPlLesson == null) {
            throw new MessageException("当前备课不存在!");
        }
        BeanUtils.copyProperties(curPlLesson, plPrepareLessonDetail);
        //当前备课创建人名称
        List<SysUserIdAndNameVo> currentCreateNameList = ThriftUtils.findUserNameByUserIdList(Arrays.asList(curPlLesson.getCreateBy()));
        if (!CollectionUtils.isEmpty(currentCreateNameList)) {
            plPrepareLessonDetail.setCreateName(currentCreateNameList.get(0).getName());
        }

        List<PlLessonClassDetail> plLessonClassDetails = plLessonClassDetailService.findPlLessonClassDetailsBySchoolIdAndLessonId(schoolId, lessonId);
        List<ClassVo> classVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(plLessonClassDetails)) {
            plLessonClassDetails.stream().forEach(item -> classVoList.add(new ClassVo(item.getClassId(),
                    item.getDistanceYear(), item.getGradeName(), item.getClassName(), item.getClassCode())));
        }
        //备课 - 班级
        plPrepareLessonDetail.setClassList(classVoList);

        List<PlLessonFile> plLessonFileList = plLessonFileService.findPlLessonFileListBySchoolIdAndLessonId(schoolId, lessonId);
        List<FilePlLessonVo> fileList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(plLessonFileList)) {
            plLessonFileList.stream().forEach(item -> {
                fileList.add(new FilePlLessonVo(item.getFileName(), item.getFilePath(), item.getSort()));
            });
        }
        //备课 - 附件
        plPrepareLessonDetail.setAnndexList(fileList);

        //备课 - 后记
        plPrepareLessonDetail.setPlPostscript(plPostScriptService.findVaildPostScriptBySchoolIdAndLessonId(schoolId, lessonId));

        return  plPrepareLessonDetail;
    }

    /**
     * 根据schoolId, lessonId, createBy 查询备课
     * @param schoolId
     * @param lessonId
     * @param createBy
     * @return
     */
    public PlLesson findValidPlLessonByIdAndCreateBy(String schoolId, String lessonId, String createBy){
        PlLessonExample example = new PlLessonExample();
        example.createCriteria().andSchoolIdEqualTo(schoolId).andStatusEqualTo(DataStatus.NORMAL.getCode())
                .andIdEqualTo(lessonId).andCreateByEqualTo(createBy);
        List<PlLesson> plLessons = plLessonMapper.selectByExample(example);
        return CollectionUtils.isEmpty(plLessons) ? null : plLessons.get(0);
    }


    /**
     * 根据schoolId, id 获取备课详情
     * @param schoolId
     * @param id
     * @return
     */
    public PlLesson findValidPlLessonBySchoolIdAndId(String schoolId, String id) {
        PlLessonExample example = new PlLessonExample();
        example.createCriteria().andSchoolIdEqualTo(schoolId).andIdEqualTo(id).andStatusEqualTo(DataStatus.NORMAL.getCode());
        List<PlLesson> plLessons = plLessonMapper.selectByExampleWithBLOBs(example);
        return CollectionUtils.isEmpty(plLessons) ? null : plLessons.get(0);
    }

    /**
     * 获取备课集合
     * @param schoolId
     * @param subjectId
     * @param schoolYear
     * @param term
     * @param lessonIdList
     * @param createBy
     * @return
     */
    public List<PlLesson> findValidPlLessonListBy(String schoolId, String subjectId, Integer schoolYear, Byte term, List<String> lessonIdList, String createBy) {
        PlLessonExample example = new PlLessonExample();
        PlLessonExample.Criteria criteria = example.createCriteria();
        criteria.andSchoolIdEqualTo(schoolId).andStatusEqualTo(DataStatus.NORMAL.getCode());
        if (StringUtils.isNotBlank(subjectId)) {
            criteria.andSubjectIdEqualTo(subjectId);
        }
        if (schoolYear != null) {
            criteria.andSchoolYearEqualTo(schoolYear);
        }
        if (term != null) {
            criteria.andTermEqualTo(term);
        }
        if (!CollectionUtils.isEmpty(lessonIdList)) {
            criteria.andIdIn(lessonIdList);
        }
        if (StringUtils.isNotBlank(createBy)) {
            criteria.andCreateByEqualTo(createBy);
        }

       return  plLessonMapper.selectByExample(example);
    }

    /**
     * 构建并保存备课与班级信息
     * @param schoolId
     * @param opeUserId
     * @param lessonId
     * @param classVoList
     */
    @Transactional(rollbackFor = Exception.class)
    public void buildAndSavePlLessonClassDetail(String schoolId, String opeUserId, String lessonId, List<ClassVo> classVoList, Date now) {
        List<PlLessonClassDetail> plLessonClassDetailList = new ArrayList<>();
        classVoList.stream().forEach(classVo -> {
            plLessonClassDetailList.add(new PlLessonClassDetail(IdUtils.newId(), lessonId, classVo.getClassId(), classVo.getDistanceYear(), classVo.getGradeName(), classVo.getClassCode(), classVo.getGradeName(), schoolId,  now, opeUserId));
        });
        plLessonClassDetailService.batchSavePlLessonClassDetail(plLessonClassDetailList);
    }

    /**
     * 构建并保存备课与附件信息
     * @param schoolId
     * @param opeUserId
     * @param lessonId
     * @param anndexList
     */
    @Transactional(rollbackFor = Exception.class)
    public void buildAndSavePlLessonFileDetail(String schoolId, String opeUserId, String lessonId,List<FilePlLessonVo> anndexList, Date now) {
        List<PlLessonFile> plLessonFileList = new ArrayList<>();
        anndexList.stream().forEach(anndex -> plLessonFileList.add(new PlLessonFile(IdUtils.newId(), anndex.getFileName(), anndex.getFilePath(), anndex.getSort(), lessonId, schoolId, opeUserId, now )));
        plLessonFileService.batchSavePlLessonFile(plLessonFileList);
    }

    /**
     * 根据schoolId 用户查找备课
     * @param schoolId
     * @param createBy
     * @return
     */
    public List<PlLesson> findValidLessonListBy(String schoolId, String createBy, List<String> lessonIdList) {
        PlLessonExample example = new PlLessonExample();
        PlLessonExample.Criteria criteria = example.createCriteria();
        criteria.andSchoolIdEqualTo(schoolId).andStatusEqualTo(DataStatus.NORMAL.getCode());
        if (StringUtils.isNotBlank(createBy)) {
            criteria.andCreateByEqualTo(createBy);
        }
        if (!CollectionUtils.isEmpty(lessonIdList)) {
            criteria.andIdIn(lessonIdList);
        }
        return  plLessonMapper.selectByExampleWithBLOBs(example);
    }

    /**
     * 根据作者获取备课集合
     * @param schoolId
     * @param createdIdList
     * @return
     */
    public List<PlLessonIdAndNameVo> findValidPlLessonListByAuthor(String schoolId, List<String> createdIdList) {
        PlLessonExample example = new PlLessonExample();
        example.createCriteria().andStatusEqualTo(DataStatus.NORMAL.getCode()).andSchoolIdEqualTo(schoolId).andCreateByIn(createdIdList);
        List<PlLesson> plLessons = plLessonMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(plLessons)) {
            return  new ArrayList<>();
        }
        List<PlLessonIdAndNameVo> list = new ArrayList<>();
        for (PlLesson plLesson : plLessons) {
            PlLessonIdAndNameVo plLessonIdAndNameVo = new PlLessonIdAndNameVo();
            plLessonIdAndNameVo.setLessonId(plLesson.getId());
            plLessonIdAndNameVo.setLessonName(plLesson.getTitle());
            list.add(plLessonIdAndNameVo);
        }
        return list;
    }

    /**
     * 根据schoolId lessonIdList 查询备课集合
     * @param schoolId
     * @param lessonIdList
     * @return
     */
    public List<PlLesson> findValidListBySchoolIdAndIdIn(String schoolId, List<String> lessonIdList) {
        PlLessonExample example = new PlLessonExample();
        example.createCriteria().andStatusEqualTo(DataStatus.NORMAL.getCode()).andSchoolIdEqualTo(schoolId).andIdIn(lessonIdList);
        return plLessonMapper.selectByExample(example);
    }

    /**
     * 软删除用户备课信息
     * @param schoolId
     * @param lessonId
     * @param userId
     */
    @Transactional(rollbackFor = Exception.class)
    public void softDeleteLesson(String schoolId, String lessonId, String userId) {
        PlLesson curPlLesson = findValidPlLessonByIdAndCreateBy(schoolId, lessonId, userId);
        if (curPlLesson == null) {
            throw  new MessageException("当前备课记录存在！");
        }
        List<PlComment> plCommentList = plCommentService.findValidPlCommentListBySchoolIdAndLessonId(schoolId, lessonId);
        if (!CollectionUtils.isEmpty(plCommentList)) {
            throw new MessageException("当前备课存在评论不能删除!");
        }
        PlPostscript plPostscript = plPostScriptService.findVaildPostScriptBySchoolIdAndLessonId(schoolId, lessonId);
        if (plPostscript != null) {
            throw new MessageException("当前备课后记评论不能删除!");
        }
        PlLesson plLessonForUpdate = new PlLesson();
        plLessonForUpdate.setId(lessonId);
        plLessonForUpdate.setUpdateBy(userId);
        plLessonForUpdate.setUpdateAt(new Date());
        plLessonForUpdate.setStatus(DataStatus.DELETE.getCode());
        plLessonMapper.updateByPrimaryKeySelective(plLessonForUpdate);

        // 删除备课文件关联关系
        plLessonFileService.batchDeletePlLessonFile(schoolId, userId, lessonId);

        //删除备课班级关联关系
        plLessonClassDetailService.batchDeletePlLessonClassDetail(schoolId, userId, lessonId);
    }

    /**
     * 查询 备课id集合
     * @param schoolId
     * @param subjectId
     * @param term
     * @param schoolYear
     * @param distanceYear
     * @param classId
     * @return
     */
    public List<String> findPlLessonIdListBy(String schoolId, String subjectId, Byte term, Integer schoolYear, BigDecimal distanceYear, String classId, String createBy) {
        List<String> lessonIdList = new ArrayList<>();

        if (StringUtils.isNotBlank(classId) || distanceYear != null) {
            List<PlLessonClassDetail> plCDListList = plLessonClassDetailService.findPlCDListByLessonIdInAndBy(schoolId, null, distanceYear, classId);
            if (!CollectionUtils.isEmpty(plCDListList)) {
                lessonIdList =   plCDListList.stream().map(PlLessonClassDetail::getLessonId).collect(Collectors.toList());
            }
        }

        if (StringUtils.isNotBlank(subjectId) || schoolYear != null || term != null ) {
            List<PlLesson> plLessonList = findValidPlLessonListBy(schoolId, subjectId, schoolYear, term, lessonIdList, createBy);
            if (!CollectionUtils.isEmpty(plLessonList)) {
                lessonIdList = plLessonList.stream().map(PlLesson::getId).collect(Collectors.toList());
            }
        }
        return lessonIdList;
    }
}
